#include("../layout.html")
#@layout("分类目录")

<!-- 宏定义：递归生成分类下拉选项 -->
#define dropdown(terms, depth)
    #for(term : terms)
        #set(indent = java.lang.String::join("", java.util.Collections::nCopies(depth, "— ")))
        <option value="#(term.termId)">#(indent + term.name)</option>
        #if(null != term.children)
            #@dropdown(term.children, depth + 1)
        #end
    #end
#end

#define head()
<style>
    .loading-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(255,255,255,0.8);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 10;
    }
</style>
#end

#define body()
<h1 class="wp-heading-inline">分类目录</h1>
<hr class="wp-header-end">

<div class="layui-fluid">
    <!-- 搜索区域 -->
	<form class="layui-form" action="">
		<div class="search-box">
			<label class="screen-reader-text" for="search-input">搜索文章:</label>
			<div class="layui-inline">
				<input type="search" id="search-input" name="s" value="" class="layui-input" placeholder="输入分类名称搜索...">
			</div>
			<div class="layui-inline">
<!--				<input type="submit" id="search-submit" class="layui-btn layui-btn-sm layui-btn-primary" value="搜索分类目录">-->
                <button type="submit" id="search-submit" class="layui-btn layui-btn-sm layui-btn-primary">
                    <i class="layui-icon layui-icon-search"></i> 搜索
                </button>
                <button type="button" id="reset-search" class="layui-btn layui-btn-sm">
                    <i class="layui-icon layui-icon-close"></i> 重置
                </button>
			</div>
		</div>
	</form>
	<div class="layui-row layui-col-space15">
        <!-- 左侧：添加分类表单 -->
		<div class="layui-col-md4">
			<h2>添加新分类目录</h2>
			<form class="layui-form tby-form-left" action="/admin/api/term/create" method="post" id="term-form">
                <input type="hidden" name="taxonomy" value="category">
				<div class="layui-form-item">
		    		<label class="layui-form-label" for="name">名称</label>
		    		<div class="layui-input-block">
		    			<input type="text" name="name" id="name" required lay-verify="required" placeholder="请输入分类名称" autocomplete="off" class="layui-input">
		   	 		</div>
		   	 		<p>这将是它在站点上显示的名字。</p>
		    	</div>
		    	<div class="layui-form-item">
		    		<label class="layui-form-label" for="slug">别名</label>
		    		<div class="layui-input-block">
		    			<input type="text" name="slug" id="slug" placeholder="分类别名（可选）" autocomplete="off" class="layui-input">
		   	 		</div>
		   	 		<p>“别名”是在URL中使用的别称，它可以令URL更美观。通常使用小写，只能包含字母，数字和连字符（-）。</p>
		    	</div>
		    	<div class="layui-form-item">
		    		<label class="layui-form-label" for="parent">父级分类目录</label>
		    		<div class="layui-input-block">
		    			<select name="parentId" id="parent">
		    				<option value="0">无</option>
                            <!-- 选项将通过JavaScript动态加载 -->
		    			</select>
		   	 		</div>
		   	 		<p>分类目录和标签不同，它可以有层级关系。您可以有一个“音乐”分类目录，在这个目录下可以有叫做“流行”和“古典”的子目录。</p>
		    	</div>
		    	<div class="layui-form-item">
		    		<label class="layui-form-label" for="description">图像描述</label>
		    		<div class="layui-input-block">
		    			<textarea name="description" id="description" placeholder="分类描述（可选）" class="layui-textarea"></textarea>
		   	 		</div>
		   	 		<p>描述只会在一部分主题中显示。</p>
		    	</div>
		    	<div class="layui-form-item">
	    			<button type="submit" lay-submit lay-filter="*" class="layui-btn layui-btn-sm">添加新分类目录</button>
	    		</div>
		    </form>
		</div>

        <!-- 右侧：分类列表 -->
		<div class="layui-col-md8">
			<h2 class="screen-reader-text">过滤文章列表</h2>

			<form id="terms-filter" class="layui-form" onsubmit="return false;">
                #@tableNav("top", "batch-top")

				<h2 class="screen-reader-text">文章列表</h2>
                <table class="layui-table" lay-skin="line" lay-even>
                    <colgroup>
                        <col width="30">
                        <col>
                        <col width="120">
                        <col width="180">
                        <col width="60">
                    </colgroup>
                    <thead>
                        <tr>
                            <th><input type="checkbox" class="select-all" lay-skin="primary" lay-filter="checkall"></th>
                            <th>名称</th>
                            <th>描述</th>
                            <th>别名</th>
                            <th>总数</th>
                        </tr>
                    </thead>
                    <tbody>
                    <!-- 动态内容将通过模板渲染 -->
                    </tbody>
                    #[[
                    <script type="text/html" id="table-template">
                        {{# layui.each(d, function(index, item){ }}
                        <tr align="left">
                            <td>
                                <input type="checkbox" name="termIds" value="{{item.termId}}" lay-skin="primary" lay-filter="termCheckbox">
                            </td>
                            <td>
                                <strong>{{item.name}}</strong>
                                <div class="row-actions">
                                    <span class="edit"><a href="javascript:void(0);" class="edit-item" data-id="{{item.termId}}" data-name="{{item.name}}" aria-label="编辑“({{item.name}})”">编辑</a> | </span>
                                    <span class="view"><a href="" rel="bookmark" aria-label="预览“({{item.name}})”">查看</a> | </span>
                                    <span class="delete"><a href="javascript:void(0);" class="delete-item" data-id="{{item.termId}}" data-name="{{item.name}}" aria-label="删除({{item.name}})">删除</a></span>
                                </div>
                            </td>
                            <td>
                                {{item.description || '-'}}
                            </td>
                            <td>
                                {{item.slug || '-'}}
                            </td>
                            <td>
                                <span>{{item.count || 0}}</span>
                                <span class="screen-reader-text">没有标签</span>
                            </td>
                        </tr>
                        {{# }); }}
                    </script>
                    ]]#
                    <tfoot>
                        <tr>
                            <th><input type="checkbox" class="select-all" lay-skin="primary" lay-filter="checkall"></th>
                            <th>名称</th>
                            <th>描述</th>
                            <th>别名</th>
                            <th>总数</th>
                        </tr>
                    </tfoot>
                </table>

                #@tableNav("bottom", "batch-bottom")
			</form>
		</div>
	</div>

</div>
#end

<!-- 宏定义：表格导航 -->
#define tableNav(postion, selectId)
<div class="tablenav #(postion)">
    <div class="alignleft actions bulk-actions">
        <label for="#(selectId)" class="screen-reader-text">选择批量操作</label>
        <div class="layui-inline">
            <select name="action" id="#(selectId)" lay-filter="batch-action">
                <option value="-1">批量操作</option>
                <option value="delete">删除</option>
            </select>
        </div>
        <div class="layui-inline">
            <input type="submit" class="layui-btn layui-btn-sm layui-btn-primary apply-btn" value="应用">
        </div>
        <div class="layui-inline selected-count">
            已选择 <span class="count">0</span> 项
        </div>
    </div>
    <div class="alignleft actions">
        <button type="button" class="layui-btn layui-btn-sm" id="refresh-btn">
            <i class="layui-icon layui-icon-refresh"></i> 刷新
        </button>
    </div>
    <div class="tablenav-pages"></div>
    <br class="layui-clear">
</div>
#end

#define foot()
<script>
    layui.define(['laypage', 'tbynet'], function(exports) {
        'use strict';

        const $ = layui.$;
        const form = layui.form;
        const layer = layui.layer;
        const laytpl = layui.laytpl;
        const laypage = layui.laypage;
        const tbynet = layui.tbynet;

        /**
         * 分类管理模块
         */
        const TermManager = {
            // 状态管理
            state: {
                keyword: '',
                currentPage: 1,
                pageSize: 20,
                isLoading: false,
                selectedCount: 0
            },

            // API 端点
            endpoints: {
                create: '/admin/api/term/create',
                list: '/admin/api/term/list',
                delete: '/admin/api/term/delete',
                batchDelete: '/admin/api/term/batch_delete',
                hierarchy: '/admin/api/term/hierarchy'
            },

            /**
             * 初始化模块
             */
            init() {
                this.bindEvents();
                this.setupFormCallbacks();
                this.loadTermList();
                this.loadParentDropdown(); // 新增：加载父级分类下拉框
            },

            /**
             * 绑定事件处理
             */
            bindEvents() {
                this.bindSearchEvents();
                this.bindCheckboxEvents();
                this.bindBatchActionEvents();
                this.bindEditEvents();
                this.bindDeleteEvents();
            },

            /**
             * 搜索相关事件
             */
            bindSearchEvents() {
                // 搜索按钮点击
                $('#search-submit').on('click', (e) => {
                    e.preventDefault();
                    this.handleSearch();
                });

                $('#reset-search').on('click', () => {
                    this.resetSearch();
                });

                // 搜索框回车
                $('#search-input').on('keypress', (e) => {
                    if (e.which === 13) {
                        e.preventDefault();
                        this.handleSearch();
                    }
                });

                // 刷新按钮
                $('#refresh-btn').on('click', () => {
                    this.refreshData();
                });
            },

            /**
             * 复选框事件
             */
            bindCheckboxEvents() {
                // 全选/全不选
                form.on('checkbox(checkall)', (data) => {
                    const isChecked = data.elem.checked;
                    $('input[name="termIds"]').prop('checked', isChecked);
                    this.updateSelectionState();
                });

                // 单个复选框
                form.on('checkbox(termCheckbox)', () => {
                    this.updateSelectionState();
                });
            },

            /**
             * 批量操作事件
             */
            bindBatchActionEvents() {
                // 批量操作应用
                $('.apply-btn').on('click', (e) => {
                    this.handleBatchAction(e.target);
                });

                // 批量操作选择框联动
                form.on('select(batch-action)', (data) => {
                    this.syncBatchSelectors(data.elem.id, data.value);
                });
            },

            /**
             * 编辑事件
             */
            bindEditEvents() {
                // 使用事件委托处理动态生成的删除按钮
                $('#terms-filter tbody').on('click', '.edit-item', (e) => {
                    e.preventDefault();
                    e.stopPropagation(); // 防止事件冒泡

                    const $target = $(e.currentTarget);
                    const termId = $target.data('id');
                    const termName = $target.data('name');

                    if (!termId) {
                        console.warn('编辑按钮缺少 termId');
                        return;
                    }

                    this.editTerm(termId);
                });
            },

            /**
             * 删除事件
             */
            bindDeleteEvents() {
                // 使用事件委托处理动态生成的删除按钮
                $('#terms-filter tbody').on('click', '.delete-item', (e) => {
                    e.preventDefault();
                    e.stopPropagation(); // 防止事件冒泡

                    const $target = $(e.currentTarget);
                    const termId = $target.data('id');
                    const termName = $target.data('name');

                    if (!termId) {
                        console.warn('删除按钮缺少 termId');
                        return;
                    }

                    this.deleteSingleTerm(termId, termName);
                });
            },

            /**
             * 设置表单回调
             */
            setupFormCallbacks() {
                // 创建分类成功回调
                tbynet.form[this.endpoints.create] = (data, required, res) => {
                    if (res.state) {
                        this.handleCreateSuccess(res);
                    } else {
                        layer.msg(res.msg || '操作失败', { icon: 2 });
                    }
                };
            },

            /**
             * 处理搜索
             */
            handleSearch: function() {
                tbynet.debounce(() => {
                    const keyword = $('#search-input').val().trim();
                    this.state.keyword = keyword;
                    this.loadTermList(1);
                }, 300)();
            },

            /**
             * 重置搜索
             */
            resetSearch() {
                $('#search-input').val('');
                this.state.keyword = '';
                this.loadTermList(1);
            },

            /**
             * 刷新数据
             */
            refreshData() {
                this.loadTermList(this.state.currentPage);
                layer.msg('数据已刷新', { icon: 1, time: 1000 });
            },

            /**
             * 处理批量操作
             */
            handleBatchAction(buttonElement) {
                const $button = $(buttonElement);
                const action = $button.closest('.bulk-actions').find('select').val();
                const termIds = this.getSelectedTermIds();

                if (action === 'delete') {
                    this.batchDeleteTerms(termIds);
                } else if (action === '-1') {
                    layer.msg('请选择批量操作', { icon: 2 });
                }
            },

            /**
             * 同步批量选择器
             */
            syncBatchSelectors(changedId, value) {
                const targetId = changedId === 'batch-top' ? 'batch-bottom' : 'batch-top';
                $(`#${targetId}`).val(value);
                form.render('select');
            },

            /**
             * 更新全选状态
             */
            updateSelectionState() {
                const $checkboxes = $('input[name="termIds"]');
                const total = $checkboxes.length;
                const checked = $checkboxes.filter(':checked').length;
                const allChecked = total > 0 && total === checked;

                this.state.selectedCount = checked;
                $('.selected-count .count').text(checked);

                $('.select-all').prop('checked', allChecked);
                form.render('checkbox');
            },

            /**
             * 获取选中的分类ID
             */
            getSelectedTermIds() {
                const termIds = [];
                $('input[name="termIds"]:checked').each(function() {
                    termIds.push($(this).val());
                });
                return termIds;
            },

            /**
             * 加载分类列表
             */
            loadTermList(page = 1) {
                if (this.state.isLoading) return;

                this.state.isLoading = true;
                this.state.currentPage = page;

                const params = {
                    taxonomies: 'category',
                    page: page,
                    size: this.state.pageSize
                };

                if (this.state.keyword) {
                    params.search = this.state.keyword;
                }

                this.showLoading();

                // 添加超时处理
                const timeoutId = setTimeout(() => {
                    if (this.state.isLoading) {
                        this.state.isLoading = false;
                        this.hideLoading();
                        layer.msg('请求超时，请重试', { icon: 2 });
                    }
                }, 10000);

                tbynet.ajax(this.endpoints.list, params, (res) => {
                    clearTimeout(timeoutId);
                    this.state.isLoading = false;
                    this.hideLoading();
                    this.renderTermList(res.data);
                }, "json").fail(() => {
                    clearTimeout(timeoutId);
                    this.state.isLoading = false;
                    this.hideLoading();
                    layer.msg('网络错误，请重试', { icon: 2 });
                });
            },

            /**
             * 加载父级分类下拉框
             */
            loadParentDropdown() {
                tbynet.ajax(this.endpoints.hierarchy, {
                    taxonomy: 'category'
                }, (res) => {
                    if (res.state) {
                        this.renderParentDropdown(res.data);
                    } else {
                        layer.msg('加载父级分类失败', { icon: 2 });
                    }
                }, "json").fail(() => {
                    layer.msg('网络错误，请重试', { icon: 2 });
                });
            },

            /**
             * 渲染父级分类下拉框
             */
            renderParentDropdown(data) {
                const $parentSelect = $('#parent');
                // 清空除了第一个选项之外的所有选项
                $parentSelect.find('option:not(:first)').remove();

                // 递归渲染选项
                const renderOptions = (terms, depth = 0) => {
                    terms.forEach(term => {
                        const indent = '— '.repeat(depth);
                        const $option = $(`<option value="${term.termId}">${indent}${term.name}</option>`);
                        $parentSelect.append($option);

                        if (term.children && term.children.length > 0) {
                            renderOptions(term.children, depth + 1);
                        }
                    });
                };

                renderOptions(data.hierarchyTerms || []);
                form.render('select');
            },

            /**
             * 显示加载状态
             */
            showLoading() {
                if ($('.loading-overlay').length === 0) {
                    $('#terms-filter').append(`
                        <div class="loading-overlay">
                            <div class="loading-content">
                                <i class="layui-icon layui-icon-loading layui-anim-rotate"></i>
                                <div>加载中...</div>
                            </div>
                        </div>
                    `);
                }
            },

            /**
             * 隐藏加载状态
             */
            hideLoading() {
                $('.loading-overlay').remove();
            },

            /**
             * 渲染分类列表
             */
            renderTermList(data) {
                const $template = $('#table-template');
                if ($template.length === 0) return;

                const terms = data.terms || [];

                // 无数据检查
                if (terms.length === 0) {
                    $('table tbody').html('<tr><td colspan="5" class="text-center">暂无数据</td></tr>');
                    return;
                }

                // XSS 防护 - 对输出内容进行转义
                terms.forEach(term => {
                    term.name = tbynet.escape(term.name);
                    term.description = tbynet.escape(term.description);
                });

                laytpl($template.html()).render(terms, (html) => {
                    $('table tbody').html(html);
                    this.renderPagination(data.total);
                    this.updateSelectionState();
                    form.render();
                });
            },

            /**
             * 渲染分页
             */
            renderPagination(total) {
                laypage.render({
                    elem: $('.tablenav-pages'),
                    count: total,
                    limit: this.state.pageSize,
                    curr: this.state.currentPage,
                    layout: ['count', 'prev', 'page', 'next'],
                    jump: (obj, first) => {
                        if (!first) {
                            this.loadTermList(obj.curr);
                        }
                    }
                });
            },

            /**
             * 编辑分类
             */
            editTerm(termId) {
                window.location.href = `/web/admin/term/edit?id=${termId}`;
            },

            /**
             * 批量删除分类
             */
            batchDeleteTerms(termIds) {
                if (!termIds.length) {
                    layer.msg('请选择要删除的分类目录', { icon: 2 });
                    return;
                }

                this.confirmDelete(
                    `确定要删除选中的 ${termIds.length} 个分类目录吗？`,
                    () => this.executeBatchDelete(termIds)
                );
            },

            /**
             * 删除单个分类
             */
            deleteSingleTerm(termId, termName) {
                this.confirmDelete(
                    `确定要删除分类"${termName}"吗？`,
                    () => this.executeSingleDelete(termId)
                );
            },

            /**
             * 确认删除对话框
             */
            confirmDelete(message, callback) {
                layer.confirm(message, {
                    title: '确认删除',
                    btn: ['确定', '取消']
                }, (index) => {
                    layer.close(index);
                    callback();
                });
            },

            /**
             * 执行批量删除
             */
            executeBatchDelete(termIds) {
                if (this.state.isLoading) return;

                this.state.isLoading = true;

                this.showLoading();

                tbynet.ajax(this.endpoints.batchDelete, {
                    termIds: termIds,
                    taxonomy: 'category'
                }, (res) => {
                    this.state.isLoading = false;
                    this.hideLoading();
                    this.handleDeleteResult(res, true);
                }, "json").fail(() => {
                    this.state.isLoading = false;
                    this.hideLoading();
                    layer.msg('网络错误，请重试', { icon: 2 });
                });
            },

            /**
             * 执行单个删除
             */
            executeSingleDelete(termId) {
                if (this.state.isLoading) return;

                this.state.isLoading = true;

                this.showLoading();

                tbynet.ajax(this.endpoints.delete, {
                    id: termId,
                    taxonomy: 'category'
                }, (res) => {
                    this.state.isLoading = false;
                    this.hideLoading();
                    this.handleDeleteResult(res);
                }, "json").fail(() => {
                    this.state.isLoading = false;
                    this.hideLoading();
                    layer.msg('网络错误，请重试', { icon: 2 });
                });
            },

            /**
             * 处理删除结果
             */
            handleDeleteResult(res, isBatch = false) {
                if (res.state) {
                    layer.msg(res.msg, { icon: 1, time: 1500 });
                    // 如果是批量删除或删除后当前页可能为空，则返回第一页
                    const targetPage = isBatch || this.state.currentPage === 1 ? 1 : this.state.currentPage;
                    this.loadTermList(targetPage);
                } else {
                    layer.msg(res.msg || '删除失败', { icon: 2 });
                }
            },

            /**
             * 处理创建成功
             */
            handleCreateSuccess(res) {
                if (res.state) {
                    layer.msg(res.msg, {
                        offset: '15px',
                        icon: 1,
                        time: 1000
                    }, () => {
                        $('#term-form')[0].reset();
                        this.loadTermList(1);
                        // 滚动到列表顶部
                        $('html, body').animate({ scrollTop: $('.layui-col-md8').offset().top }, 500);
                    });
                } else {
                    layer.msg(res.msg || '操作失败', { icon: 2 });
                }
            },

            /**
             * 处理更新成功
             */
            handleUpdateSuccess(res) {
                layer.msg(res.msg, {
                    offset: '15px',
                    icon: 1,
                    time: 1000
                }, () => {
                    window.location.href = '/web/admin/term';
                });
            }
        };

        // 初始化分类管理
        $(document).ready(() => {
            TermManager.init();
        });

        // 提供全局访问
        // window.TermManager = TermManager;
        // exports('category', TermManager);
    });
</script>
#end